/**
 * @file skoll.tools.modalwindow.js
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: skoll.tools.modalwindow.js 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/skins/Skoll/js/skoll.tools.modalwindow.js $
 */

/**
 * Skoll skin modal windows manager.
 */
Skoll.tools.ModalWindow = {
	//
	// Protected properties.
	_closeListeners: [],
	//
	// Public methods.
	addCloseListener: function(listener) {
		Skoll.tools.ModalWindow._closeListeners.push(listener);
	},
	closeModal: function() {
		Skoll.tools.preventDefault();
		$("#SkollModalDialog").dialog("close");
	},
	modal: function(config) {
		if ($("#SkollModalDialog").dialog("isOpen")) {
			$("#SkollModalDialog").dialog(config);
		}
	},
	openModal: function(url, callback) {
		Skoll.tools.log("ModalWindow.openModal(): Url: " + url);
		Skoll.tools.Loading.start(0);

		$.ajax({
			url: url + "&nolayout",
			type: "GET",
			success: function(data) {
				Skoll.tools.ModalWindow.openSimpleModal(data, callback);

				Skoll.tools.Loading.stop();
			},
			error: function(data) {
				Skoll.tools.log("ModalWindow.openModal(): Unable to open ': " + url + "'");
				Skoll.tools.log(data);

				Skoll.tools.Loading.stop();
			}
		});
	},
	openSimpleModal: function(data, callback) {
		if (typeof callback != "undefined") {
			Skoll.tools.ModalWindow.addCloseListener(callback);
		}
		$("body").append('<div id="SkollModalDialog"></div>');

		$("#SkollModalDialog").html(data);
		if ($("#SkollModalDialog").hasClass("Bermuda")) {
			$("#SkollModalDialog").removeClass("Bermuda");
		}

		$("#SkollModalDialog").dialog({
			close: function(event) {
				Skoll.tools.ModalWindow._fireCloseListeners();
				$(this).dialog("destroy");
				$("#SkollModalDialog").remove();
			},
			closeOnEscape: true,
			modal: true,
			width: "auto"
		});


		$("[modal-title]").each(function() {
			Skoll.tools.ModalWindow.modal({
				title: $(this).attr("modal-title")
			});
		});

		setTimeout(function() {
			$("#SkollModalDialog").dialog({
				position: "center"
			});
		}, 200);
		setTimeout(function() {
			$("#SkollModalDialog").dialog({
				position: "center"
			});
		}, 1000);
	},
	//
	// Protected methods.
	_fireCloseListeners: function() {
		Skoll.tools.ModalWindow._closeListeners.forEach(function(listener) {
			var type = typeof listener;

			if (type == "function") {
				listener();
			} else if (type == "string") {
				Skoll.tools.log(listener);
			}

			Skoll.tools.ModalWindow._closeListeners.splice(Skoll.tools.ModalWindow._closeListeners.indexOf(listener), 1);
		});
	}
};